from datetime import datetime, timedelta
import json
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.extensions import scheduler
from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings
from application.tasks import formcollection_task


router = APIRouter(prefix='/code', tags=['Code'])
module_name = '码管理模块 - 扫码日志'


@router.get('/codelogs', response_model=schemas.BaseApiListOut)
async def get_code_logs(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    code: Optional[str] = None,
    start_time: Optional[str] = None,
    end_time: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """
        码管理 扫码列表
    """

    objs = OemModel.CodeLog.with_('brand')

    if start_time is not None and start_time != '' and end_time is not None and end_time != '':
        objs = objs.where_between('created_at', [start_time + ' 00:00:00', end_time + ' 23:59:59'])

    if code:
        objs = objs.where('code', code)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'batch', 'like', f'%{keyword}%'
            ).or_where(
                'security_code', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.get('/codelogs/collections', response_model=schemas.BaseApiListOut)
async def get_codelog_collections(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    brand_id: Optional[int] = None,
    start_time: Optional[str] = None,
    end_time: Optional[str] = None,
    batch_sn: Optional[str] = None,
    security_code: Optional[str] = None,
    serial_number: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """码管理 表单收集列表

        # 创建表测试
        OemModel.CodeCollection.create_table()
        OemModel.AssetCategory.create_table()
        OemModel.Asset.create_table()
        OemModel.Download.create_table()
    """
    objs = OemModel.CodeCollection.with_('brand').with_('codelog')

    # 时间限制
    if start_time is not None and start_time != '' and end_time is not None and end_time != '':
        objs = objs.where_between('created_at', [start_time + '00:00:00', end_time + '23:59:59'])
    # 品牌限制
    if brand_id:
        objs = objs.where('brand_id', brand_id)
    # 批次信息
    if batch_sn:
        objs = objs.where('batch_sn', batch_sn)
    # 防伪码
    if security_code:
        objs = objs.where('security_code', security_code)
    # 序列号
    if serial_number:
        objs = objs.where('serial_number', serial_number)
    # 关键词搜索 姓名、手机搜索
    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'name', 'like', f'%{keyword}%'
            ).or_where(
                'phone', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('/codelogs/collections', response_model=schemas.BaseApiListOut)
async def download_codelog_collections(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: dict = Body(...),
):
    """
        码管理 表单收集列表 下载单提交
    """

    # 下载任务单创建
    try:
        obj_download = OemModel.Download.create({
            'type': 2,  # 类型 1 - 码订单导出 2 - 表单收集导出
            'params': json.dumps(post),
            'position': 0,
            'status': 0,
            'admin_id': current_user.id,
            'name': f'表单收集_{datetime.now().strftime("%Y%m%d%H%M")}',
        })

        obj_download = obj_download.fresh()

        # 异步处理任务启动
        job = scheduler.enqueue_at(
            datetime.now() + timedelta(seconds=3),
            formcollection_task.export_job,
            args=[obj_download.id],
            job_id=f'collection_export_{obj_download.id}',
            description=f'表单收集-{obj_download.id}',
            timeout=16600,
            kwargs={**post}
        )

        return {'message': '操作成功', 'data': {'id': obj_download.fresh().id, 'job_id': job.get_id(), 'job_status': job.get_status()}}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')
